package com.alan.product.issue.threadpool;

import com.alan.product.issue.entity.User;
import com.alan.product.issue.util.UserContext;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Supplier;

public class MyThreadPool {

    private static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(4);

    public static void execute(Runnable command) {
        User user = UserContext.getUser();
        THREAD_POOL.execute(()->{
            UserContext.setUser(user);
            try {
                command.run();
            } finally {
                UserContext.removeUser();
            }
        });
    }

    public static <T> Future<T> submit(Supplier<T> command) {
        User user = UserContext.getUser();
        return THREAD_POOL.submit(()->{
            UserContext.setUser(user);
            try {
                return command.get();
            } finally {
                UserContext.removeUser();
            }
        });
    }

}
